package com.whfc.fuum.redis.impl;

import com.whfc.common.util.JSONUtil;
import com.whfc.fuum.dto.SysMachTypeDTO;
import com.whfc.fuum.redis.MachTypeRedisDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @ClasssName MachTypeRedisDaoImpl
 * @Description 设备类型缓存类
 * @Author hw
 * @Date 2020/10/23 9:22
 * @Version 1.0
 */
@Component
public class MachTypeRedisDaoImpl implements MachTypeRedisDao {

    private static final String MACH_TYPE_CACHE_ID = "mach-type-cache-id";

    private static final String MACH_TYPE_CACHE_CODE = "mach-type-cache-code";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    @Override
    public void setMachType(SysMachTypeDTO sysMachType) {
        if (sysMachType == null) {
            return;
        }
        Integer machTypeId = sysMachType.getMachTypeId();
        String code = sysMachType.getCode();
        SysMachTypeDTO data = this.getMachType(machTypeId);
        if (data != null) {
            //存在缓存先删除历史缓存在更新
            this.delete(sysMachType);
        }
        String json = JSONUtil.toString(sysMachType);
        redisTemplate.opsForHash().put(MACH_TYPE_CACHE_ID, String.valueOf(machTypeId), json);
        redisTemplate.opsForHash().put(MACH_TYPE_CACHE_CODE, code, json);

    }


    @Override
    public SysMachTypeDTO getMachType(Integer machTypeId) {
        String data = (String) redisTemplate.opsForHash().get(MACH_TYPE_CACHE_ID, String.valueOf(machTypeId));
        if (data == null) {
            return null;
        }
        SysMachTypeDTO sysMachTypeDTO = JSONUtil.parseObject(data, SysMachTypeDTO.class);
        return sysMachTypeDTO;
    }

    @Override
    public SysMachTypeDTO getMachType(String code) {
        String data = (String) redisTemplate.opsForHash().get(MACH_TYPE_CACHE_CODE, code);
        if (data == null) {
            return null;
        }
        SysMachTypeDTO sysMachTypeDTO = JSONUtil.parseObject(data, SysMachTypeDTO.class);
        return sysMachTypeDTO;
    }

    @Override
    public SysMachTypeDTO getParentMachType(Integer machTypeId) {
        SysMachTypeDTO data = this.getMachType(machTypeId);
        if (data == null) {
            return null;
        }
        return this.getMachType(data.getPid());
    }

    @Override
    public SysMachTypeDTO getParentMachType(String code) {
        SysMachTypeDTO data = this.getMachType(code);
        if (data == null) {
            return null;
        }
        return this.getMachType(data.getPid());
    }

    @Override
    public void delete(SysMachTypeDTO sysMachType) {
        String code = sysMachType.getCode();
        Integer machTypeId = sysMachType.getMachTypeId();
        redisTemplate.opsForHash().delete(MACH_TYPE_CACHE_CODE, code);
        redisTemplate.opsForHash().delete(MACH_TYPE_CACHE_ID, String.valueOf(machTypeId));
    }
}
